import { useState, useRef, useEffect } from "react";
import styles from "./index.less";
import {
    motion,
    useDragControls,
} from "motion/react";

type Size = {
    width: number;
    height: number;
};

export default () => {

    const containerRef = useRef<HTMLDivElement>(null);

    const controls = useDragControls();

    const [size, setSize] = useState<Size>({ width: 0, height: 0 });

    const [dragMode, setDragMode] = useState<true | 'x' | 'y'>(true);

    useEffect(() => {
        const rect = containerRef?.current?.getBoundingClientRect();
        setSize({ width: rect?.width || 500, height: rect?.height || 300 });
    }, []);

    function startDrag(event: any) {
        controls.start(event, { snapToCursor: false });
    }

    return (
        <div className={styles.container}>
            <p>在虚线框内拖动元素</p>

            <div onPointerDown={startDrag} className={styles.dragBar} onMouseDown={() => {
                setDragMode('x');
            }}>
                也可以通过橙色拖动条移动元素
            </div>

            <div ref={containerRef} className={styles.card}>
                <motion.div
                    className={styles.motionView}
                    onMouseDown={() => {
                        setDragMode(true);
                    }}
                    drag={dragMode}
                    dragControls={controls}
                    dragConstraints={{
                        left: -(size.width - 100) / 2,
                        right: (size.width - 100) / 2,
                        top: -(size.height - 100) / 2,
                        bottom: (size.height - 100) / 2,
                    }}
                    dragElastic={0.5}// 弹性，值越大越弹
                    dragMomentum={true}// 惯性
                    onDragStart={(event, info) => console.log(info.point.x, info.point.y)}
                    onDragEnd={(event, info) => console.log(info.point.x, info.point.y)}
                >
                    M
                </motion.div>
            </div>
        </div>
    );
}